import json
import random
import string
import uuid

# Create your views here.
from django.utils.decorators import method_decorator
from django.http import JsonResponse, HttpResponse
from rest_framework import viewsets, permissions, exceptions
from rest_framework.decorators import api_view, permission_classes
from rest_framework.response import Response
from django.views.decorators.csrf import csrf_exempt
from rest_framework.views import APIView
from rest_framework.authentication import BaseAuthentication
from mainapp.models import User, UserToken
from mainapp.utils import cache
from mainapp.utils.authview import MyAuthentication
from mainapp.utils.sms import sendcode


@method_decorator(csrf_exempt,name='dispatch')
class LoginLView(APIView):
    """
    用户登录和注册。
    """
    # HttpResponse  JsonResponse  Response
    authentication_classes = []
    permission_classes = []
    def get(self,request):
        # self.dispatch()
        if hasattr(request.user,'is_login'):
            if request.user.is_login == True:
                return JsonResponse({'code':405,'msgs':'用户已登录，不能重复登录！'})
        phone = request.GET.get('phone')
        print(phone)
        # security_code = form.get('code',None)
        # user = User.objects.filter(phone=phone).values('name','phone')[0]
        # user = User.objects.get(pk=1)
        user = User.objects.filter(phone=phone).first()
        print(user)
        # request.user
        # request.auth
        if user is not None:
            # update the token
            user.is_login = True
            token = uuid.uuid4().hex
            # 存在就跟新，不存在就创建
            UserToken.objects.update_or_create(user=user,defaults={'token':token})
            return JsonResponse({'code':200,'msgs':'登录成功','token':token})
        return JsonResponse({'code':405,'msgs':'用户不存在或未登录'})

    # 注册操作
    def post(self,request,*args,**kwargs):
        # phone = request.date.get('phone',None)
        form = json.loads(request.body.decode('utf-8'))
        print(form.get('phone','name'))
        user = User()
        user.name = form.get('name',None)
        user.phone = form.get('phone',None)
        user.username = form.get('username',None)
        user.password = form.get('password',None)
        user.sex = form.get('sex',None)
        user.icon = form.get('icon',None)
        user.address = form.get('address',None)

        user.save()
        return JsonResponse({'code':200,'msgs':'注册成功'})

    # def delete(self,request):
    #     # 注销用户
    #     if 'Authorization' in request.headers:
    #         auth = request.headers.get('Authorization')
    #         print('Token----->',auth )
    #         # 验证用户权限
    #         if auth:
    #             ut_obj = UserToken.objects.filter(token=auth).first()
    #             uid = ut_obj.user_id
    #             user = User.objects.get(pk=uid)
    #             user.is_login = False
    #             # 查询与Token帮助的用户，取消绑定
    #             return JsonResponse({'code':'202','msg':'退出登录'})
    #     return JsonResponse({'code':'409','msg':'用户未登录'})


class SendCode(APIView):
    authentication_classes=[]
    permission_classes = []
    def get(self, request,*args,**kwargs):
        phone = request.query_params.get('phone')
        code = ''
        for i in range(4):
            code += random.choice(string.ascii_letters)
        if cache.has(phone):
            return JsonResponse({'code': 400, 'msg': '2分钟只能发一次'})
        sendcode(phone,code)
        return JsonResponse({'code': 200, 'msg': 'security_code','data':code})


class LogoutLView(APIView):
    def delete(self, request, *args, **kwargs):
        request.user.is_login = False
        # 查询与Token帮助的用户，取消绑定
        return JsonResponse({'code': '202', 'msg': '退出登录'})

@method_decorator(csrf_exempt,name='dispatch')
class UserHome(APIView):
    def get(self,request):
        user = request.user
        data = {
            'name':user.name,
            'phone':user.phone,
            'password':user.password,
            'address':user.address,
            'icon':user.icon
        }
        return JsonResponse({'code': 200, 'msg': 'ok','data':data})
    def put(self,request):
        form = json.loads(request.body.decode('utf-8'))
        user = User()
        user.name = form.get('name',None)
        user.phone = form.get('phone',None)
        user.password = form.get('password',None)
        user.icon = form.get('icon',None)
        user.address = form.get('address',None)

        user.save()
        return JsonResponse({'code': 200, 'msg': '信息更新成功'})


